package com.pattern.behavioural;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Ping
 * @date 2022/5/3 14:20
 **/
public class MediatorDemo {
    public static void main(String args[]) {
        Member zhangsan = new Member("zhangsan") ;
        Member lisi = new Member("lisi") ;
        IChatRoom chatRoom = new DefaultChatRoom() ;
        /*
        Binding structural relation
         */
        chatRoom.joinMember(zhangsan);
        chatRoom.joinMember(lisi);
        /**
         * structral interaction.
         */
        zhangsan.send("lisi", "Hello, lisi");

    }

}

/**
 * Mediator role:
 */
interface IChatRoom {
    public void joinMember(Member member) ;
    public void transfer(String from, String to, String msg) ;
}

abstract class AbstractChatRoom implements IChatRoom {
    Map<String, Member> members ;

    public AbstractChatRoom() {
        members  = new HashMap<>() ;
    }
    @Override
    public void joinMember(Member member) {
        this.members.put(member.getName(), member) ;
        member.joinChatRoom(this);
    }
}

/**
 * Concrete Mediator.
 */
class AuditChatRoom extends AbstractChatRoom {
    @Override
    public void transfer(String from, String to, String msg) {
        System.out.println(String.format("TRANSFER_MSG: after audited processed : %s. FROM [%s] TO [%s]", msg, from, to)) ;
        this.members.get(to).recv(from, msg);
    }
}

/**
 * Concrete Mediator.
 */
class DefaultChatRoom extends AbstractChatRoom {
    public DefaultChatRoom() {
        super() ;
    }
    /**
     * On Behaviroual level
     * @param from
     * @param to
     * @param msg
     */
    @Override
    public void transfer(String from, String to, String msg) {
        System.out.println(String.format("TRANSFER_MSG: %s. FROM [%s] TO [%s]", msg, from, to)) ;
        this.members.get(to).recv(from, msg);
    }
}

class Member {
    private String name ;
    /**
     * related to one chatRoom.
     */
    private IChatRoom chatRoom ;

    public Member(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void joinChatRoom(IChatRoom chatRoom) {
        this.chatRoom = chatRoom ;
    }
    public void send(String to, String msg) {
        System.out.println(String.format("SEND_MSG: %s. From [%s] TO [%s].", msg, this.name, to)) ;
        chatRoom.transfer(this.name, to, msg);
    }
    public void recv(String from, String msg) {
        System.out.println(String.format("RECV_MSG: %s. From [%s] TO [%s].", msg, from, this.name)) ;
    }
}
